import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'
import { config } from '@/config'

export const Layout = () => import('@/layout/index.vue') // 引入Layout组件

// 静态路由
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('@/views/home/index.vue'),
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
  },
]
/**
//  * 创建路由
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

const getAccessToken = () => {
  return localStorage.getItem(config.accessToken) || ''
}

router.beforeEach((to, from, next) => {
  const token = getAccessToken()
  console.log(`token ==>`, token)
  if (!token && to.path !== '/login') {
    next('/login')
  }
  next()
})
// 全局注册 router
export function setupRouter(app: App<Element>) {
  app.use(router)
}

/**
 * 重置路由
 */
export function resetRouter() {
  router.replace({ path: '/login' })
  location.reload()
}

export default router
